import * as cheerio from 'react-native-cheerio';
import { ISearchResult } from "../def";
import { SupportVideoType, VideoIntroduceInfo, VideoDetailInfo, VideoItem, PlaySource, Episode } from "../icommon/index";
async function search<T extends SupportVideoType>(query: string, page: number, type: T): Promise<ISearchResult<T>> {
    const movies: VideoItem[] = [];
    let url = "";
    switch (type) {
        case "movies":
            url = `https://www.ylys.tv/vodshow/1--------${page}---/`;
            break;
        case "tv":
            url = `https://www.ylys.tv/vodshow/2--------${page}---/`;
            break;
        case "cartoon":
            url = `https://www.ylys.tv/vodshow/4--------${page}---/`;
            break;
        case "all":
            url = `https://www.ylys.tv/vodsearch/${query}--------${page}---/`
            break;
    }
    console.log(url);
    const res = await fetch(url, {
        headers: {
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        },
    });
    const html = await res.text();
    const $ = cheerio.load(html);
    const listContent = $(".module-poster-items-base").find("a");
    console.log(listContent.length);
    listContent.each((index: number, element: any) => {
        const url = $(element).attr("href");
        const title = $(element).attr("title");
        const img = `https://www.ylys.tv${$(element).find(".lazyload").attr("data-original")}`;
        const id = url.match(/\/voddetail\/(\d+)\//)?.[1];
        // console.log(id, title, img);
        if (id && title && img) {
            movies.push({
                id,
                title,
                img,
                detailUrl: url
            });
        }
    });

    return {
        data: movies,
        isEnd: movies.length <= 0,
    } as ISearchResult<T>;
}

async function fetchIntroduceInfo({ id, url }: { url: string, id: string }): Promise<VideoIntroduceInfo> {
    let target = `https://www.ylys.tv${url}`;
    const res = await fetch(target, {
        headers: {
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        },
    });
    const html = await res.text();
    const $ = cheerio.load(html);
    const img = $(".ls-is-cached").attr("data-original");
    const title = $(".ls-is-cached").attr("alt");
    const mainInfo = $('.module-info-main');
    const introduce = mainInfo.find(".module-info-introduction-content").text().trim();
    const otherBase = mainInfo.find(".module-info-tag-link");
    const year = otherBase.eq(0).text().trim();
    const area = otherBase.eq(1).text().trim();
    const category = otherBase.eq(2).text().trim();
    const detailUrl = mainInfo.find(".module-mobile-play").find("a").attr("href");
    const ds = mainInfo.find(".module-info-item-content");
    const director = ds.eq(0).text().trim();
    const actor = ds.eq(1).text().trim();
    const updateTime = ds.eq(4).text().trim();
    return {
        id,
        title,
        img: `https://www.ylys.tv${img}`,
        introduce,
        actor,
        category,
        area,
        year,
        updateTime,
        detailUrl,
        director,
    };
}

async function fetchVideoDetailInfo({ id, url, source, episodeIndex }: {
    url: string
    id: string,
    source?: number,
    episodeIndex?: number
}): Promise<VideoDetailInfo> {
    let target = `https://www.ylys.tv${url}`;
    const res = await fetch(target, {
        headers: {
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        },
    });
    const html = await res.text();
    const $ = cheerio.load(html);

    const title = $("title").text().trim();

    const img = $("meta[property='og:image']").attr("content");

    const introduce = title;
    const detailUrl = $(".module-play-list-link.active").attr("href");
    const episodes: Episode[] = [];
    const playSources: PlaySource[] = [];
    $(".module-play-list-link").each((index: number, element: any) => {
        const title = $(element).attr("title");
        const sourceUrl = $(element).attr("href");
        const urlMatch = sourceUrl.match(/\/play\/(\d+)-(\d+)-(\d+)\//);
        console.log(title, sourceUrl);
        if (urlMatch && title && sourceUrl) {
            episodes.push({
                id: urlMatch[1],
                sourceIndex: parseInt(urlMatch[2], 10),
                episodeIndex: parseInt(urlMatch[3], 10),
                title: title,
                url: sourceUrl
            });
        }
    });
    const urlMatch = detailUrl.match(/\/play\/(\d+)-(\d+)-(\d+)\//);
    const parseSource = parseInt(urlMatch[2], 10) + "";
    const parseEspi = parseInt(urlMatch[3], 10);

    $(".module-tab-items-box").find(".module-tab-item").each((index: number, element: any) => {
        const sourceName = $(element).text().trim();
        playSources.push({
            id: parseSource,
            name: sourceName,
            episodes: episodes
        })
    });


    // 获取当前播放的视频信息
    const scriptText = html;

    // 步骤1：匹配变量声明的起始部分
    const startRegex = /var\s+player_aaaa\s*=\s*\{/;
    const startMatch = scriptText.match(startRegex);

    let videoUrl = "";

    if (!startMatch) {
        console.log("未找到player_aaaa变量声明");
    } else {
        // 步骤2：从第一个{开始截取剩余字符串
        const remainingStr = scriptText.split(startMatch[0])[1];


        // 步骤3：平衡匹配花括号，找到完整的JSON结束位置
        let braceCount = 1; // 已找到1个{
        let endIndex = 0;

        for (let i = 0; i < remainingStr.length; i++) {
            const char = remainingStr[i];
            if (char === '{') {
                braceCount++;
            } else if (char === '}') {
                braceCount--;
                if (braceCount === 0) {
                    endIndex = i; // 找到最后一个}的位置
                    break;
                }
            }
        }

        if (braceCount === 0) {
            // 提取完整的JSON字符串（包含外层{}）
            const jsonStr = '{' + remainingStr.slice(0, endIndex + 1);

            try {
                const playerConfig = JSON.parse(jsonStr);

                console.log("player_aaaa:", playerConfig);

                if (playerConfig.url) {
                    videoUrl = playerConfig.url;
                }

            } catch (e) {
                console.error("JSON解析失败：", e, "提取的字符串：", jsonStr);
            }
        } else {
            console.log("未找到完整的JSON结构（花括号不匹配）");
        }
    }

    // 如果没有从player_aaaa中获取到URL，则尝试其他方式
    if (!videoUrl) {
        // 提取视频播放地址
        const urlMatch = scriptText.match(/"url":\s*"([^"]+)"/);
        if (urlMatch) {
            videoUrl = urlMatch[1].replace(/\\\//g, '/').replace(/\\(.)/g, '$1');
        }
    }

    return {
        id,
        title,
        introduce,
        img,
        playSources,
        detailUrl,
        currentVideoInfo: {
            id,
            currentEpisode: parseEspi,
            videoUrl: videoUrl,
            currentSource: parseSource
        }
    };
}


module.exports = {
    label: "永乐视频",
    appVersion: "1.0.0",
    platform: "ynds",
    srcUrl: "https://www.ylys.tv",
    author: "petter.he",
    description: "ynds",
    enabledSearch: false,
    search,
    fetchIntroduceInfo,
    fetchVideoDetailInfo,

}